const router = require("koa-router")();
const { getUserIdByContext, getImage } = require('../token')
const ArticleComment = require('../../model/ArticleComment')
const UserBasic = require('../../model/UserBasic')
const ArticleBasic = require('../../model/ArticleBasic')
const UserRelation = require('../../model/UserRelation')
const CommentLiking = require('../../model/CommentLiking')

const  UserMessage = require('../../model/UserMessage')
const { sendMessageByUserId } = require('../websocket')

const UUID = require('uuid');
// 获取所有频道
router.get('/', async (ctx, next) => {
    const user_id = await getUserIdByContext(ctx) // 获取userId
    let { type, source, offset, limit = 10 } = ctx.request.query
    if (!type || !source) {
        return  { message: '评论类型或者来源id不能为空', status: 400}
    }
    limit = parseInt(limit)
    let current_total = 0
    let end_id = null, last_id = null, skip = 0
    let results = []
    let matchCond = null
    if (type === 'a') {
      // 获取文章的评论
      matchCond = { article_id: source, parent_id: null }
      current_total = await  ArticleComment.find({ article_id: source, parent_id: null }).countDocuments() // 当前的总数
    }else {
      // 获取评论的评论
      matchCond = { parent_id: source }
      current_total = await  ArticleComment.find({ parent_id: source }).countDocuments()
    }
    // 获取当前请求条件下的所有评论数据
    const allComments = await ArticleComment.find(matchCond).sort({ '_id': 1 }).limit(1).lean() // 所有评论
    if (offset) {
      const _id = (await ArticleComment.findOne({ comment_id: offset }).lean())._id
      let matchConCom  = { _id: { $lt: _id }, parent_id: source }
      if (type === "a") {
         matchConCom  = { _id: { $lt: _id }, parent_id: null, article_id: source  }
      }
      const  count = await ArticleComment.find(matchConCom).countDocuments()
      skip = current_total - count
      matchCond = { ...matchCond }
    }
    results =  await ArticleComment.find(matchCond).sort({ _id: -1 }).skip(skip).limit(limit)
    const users = await UserBasic.find({}).lean()
    const userRs = await UserRelation.find({}).lean()
    const commentLs = await CommentLiking.find({}).lean()
  
    if (results && results.length) {
      //   找到本次查询最后一个id
      last_id = results[results.length - 1]['comment_id']
    }
    if(allComments && allComments.length) {
      // 找到所有符合条件的最后一个id
      end_id = allComments[0]['comment_id']
    }
    if (!results.length && end_id ) {
      end_id = null
    }
    // 处理字段
    results = results.map(item => ({
      com_id: item.comment_id,
      content: item.content,
      reply_count: item.reply_count,
      pubdate: item.create_time,
      is_top: item.is_top,
      is_followed: userRs.some(obj => obj.target_user_id === item.user_id && obj.user_id === user_id),
      is_liking: commentLs.some(obj => obj.comment_id === item.comment_id && obj.user_id === user_id), // 当前用户是否对当前评论点赞
      like_count: commentLs.filter(obj => obj.comment_id === item.comment_id).length, // 当前评论的点赞数量
      aut_id: item.user_id,
      aut_name: users.find(obj => obj.user_id === item.user_id) ? users.find(obj => obj.user_id === item.user_id).user_name : '无名氏' ,
      aut_photo: users.find(obj => obj.user_id === item.user_id)  ? getImage(users.find(obj => obj.user_id === item.user_id).profile_photo) : null,
    }))
    ctx.status = 200
    return  {
      data: {
        total_count: current_total,
        end_id,
        last_id,
        results
      }
    }
})
// 发表评论
router.post('/', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target, content, art_id } = ctx.request.body
     if (!user_id) {
       return { success: false, message: '用户未认证', status: 401 }
     }
     if (!target || !content) {
       return { success: false, message: '评论内容或者评论目标为空', status: 400 }
     }
    const comment_id = UUID.v4()
    // 判断是对文章还是对评论进行评论
    let  parent_id = target 
  
    let content_copy = '回复了你的评论'
    let target_copy = ""
    let targetUserId = null
    if (!art_id || (art_id ===  target)) {
      // 如果文章id没有就是对文章进行评论
      // 如果文章id和目标id一致 也就是对文章进行评论
      parent_id = null
      content_copy = '评论了你的文章'
      // 文章id
     const artileCommentCount = await ArticleComment.find({  article_id: target }).countDocuments() // 文章的评论数
     await  ArticleBasic.findOneAndUpdate({ article_id: target }, {  comment_count: artileCommentCount + 1 }) // 更新到回复数量
     const articleInfo = await ArticleBasic.findOne({ article_id: target })
     target_copy = articleInfo ? articleInfo.title : '网络文章'
     targetUserId = articleInfo ? articleInfo.user_id : '1111'

    }else {
      const commonInfo = await ArticleComment.findOne({ comment_id: target })
     targetUserId = commonInfo.user_id
      target_copy = commonInfo.content
      const artileCommentCount = await ArticleComment.find({  article_id: commonInfo.article_id }).countDocuments() // 文章的评论数
      await  ArticleBasic.findOneAndUpdate({ article_id: commonInfo.article_id  }, {  comment_count: artileCommentCount + 1 }) // 更新到回复数量
    }
    const obj =  await  ArticleComment.create({ user_id,  comment_id, article_id: art_id || target, content, parent_id  })
    const userFile = await UserBasic.findOne({ user_id }).lean()
    // 统计回复数量
    const reply_count = await ArticleComment.find({ parent_id: target }).countDocuments() // 获取该对象评论的总数 
    // 更新到评论列表数据中
    
    await  ArticleComment.findOneAndUpdate({ comment_id: target }, {  reply_count }) // 更新到回复数量

    const new_obj = {
      "com_id": comment_id,
      "aut_id": user_id,
      "pubdate": obj.create_time,
      "content": obj.content,
      "is_top": 0,
      "aut_name":  userFile.user_name,
      "aut_photo":getImage(userFile.profile_photo),
      "like_count": 0,
      "reply_count": 0,
      "is_liking": false
    }
    ctx.status = 201
    const UserInfo = await UserBasic.findOne({ user_id })
    await UserMessage.create({type: "2", message_id: UUID.v4(), title: UserInfo.user_name, content: content_copy, user_id: targetUserId, comment_target: target_copy, comment_content: content  })
    const userProfle = await UserBasic.findOne({ user_id })
    sendMessageByUserId(targetUserId, "comment notify", {
        user_id,
        user_name: userProfle.user_name,
        user_photo: getImage(userProfle.profile_photo),
        timestamp: new Date().getTime(),
        art_id: target
    })
    return {  data: { target, art_id, com_id: comment_id, new_obj }  } 
})
module.exports = router.routes();
